package kr.re.etri.snsenabler.server;

import javax.servlet.http.HttpSession;

import kr.re.etri.snsenabler.server.db.SnsEnablerDbService;
import kr.re.etri.snsenabler.shared.SocialServiceProvider;

import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.Api;
import org.scribe.oauth.OAuthService;

abstract class AbstractSocialServiceServlet extends AbstractServiceServlet {

	private static final String REDIRECT_URI = "http://snsenabler.appspot.com/";

	protected SnsEnablerDbService getDbService() {
		return (SnsEnablerDbService)getThreadLocalRequest().getSession().getServletContext().getAttribute(Constants.DB_SERVICE);
	}

	protected OAuthService getService(SocialServiceProvider socialServiceProvider) {
		HttpSession session = super.getThreadLocalRequest().getSession();
		OAuthService service = (OAuthService)session.getAttribute(SessionAttributes.OAUTH_SERVICE + "_" + socialServiceProvider.getName());
		if (service == null) {
			if (getRedirectUri() == null) {
				service = new ServiceBuilder().provider(getApi()).apiKey(getConsumerKey()).apiSecret(getConsumerSecret()).build();
			} else {
				service = new ServiceBuilder().provider(getApi()).apiKey(getConsumerKey()).apiSecret(getConsumerSecret()).callback(getRedirectUri()).build();
			}

			session.setAttribute(SessionAttributes.OAUTH_SERVICE + "_" + socialServiceProvider.getName(), service);
		}
		return service;
	}

	protected abstract Class<? extends Api> getApi();

	protected abstract String getConsumerKey();

	protected abstract String getConsumerSecret();

	protected String getRedirectUri() {
		return REDIRECT_URI;
	}
}
